package com.scalar.chiptrack.marketing.parser;

import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.marketing.Pricing;
import com.scalar.chiptrack.marketing.dao.PricingDAO;
import com.scalar.ScalarException;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;

import jxl.Workbook;
import jxl.Sheet;
import jxl.Cell;
import jxl.CellType;

/**
 * User: ChandraSekhar
 * Date: Jul 23, 2007
 * Time: 11:48:18 AM
 */
public class PriceSetupParser extends JobHandler implements AdaptorConstants
{
    private static final String LINE_SEPARATOR = System.getProperty("line.separator");

    private Logger m_parserLogger       = null;
    private String m_dataOutputDir      = null;

    public  PriceSetupParser() throws ScalarException
    {
        try
        {
            m_dataOutputDir = ConfigManager.getPriceSetupPortingDirectory();

            AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
            m_parserLogger = AdaptorUtils.getDataParserLogger( m_dataOutputDir,"PriceSetup" );

        }
        catch ( Exception se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while getting output directory details from database, Exception: " + se );
        }
    }

    public static void main( String args[] ) throws Exception
    {
        try
        {
            new PriceSetupParser().execute();
        }
        catch( Exception e )
        {
            throw e;
        }
    }

    public void execute() throws Exception
    {
        printHeader();

        File doneDestDir = new File( m_dataOutputDir + "/done" );
        File dataoutDir  = new File( m_dataOutputDir );

        File[] fileList = dataoutDir.listFiles();

        if ( ( fileList == null ) || (fileList.length <= 3))
        {
            log("No file found in directory: " + dataoutDir);
            System.out.println("\n\n---No file found in directory: " + dataoutDir  + "----\n\n");
            throw new ScalarException("\n\n---No file found in directory: " + dataoutDir + "----\n\n" );
        }

        DBTransaction dbTransaction = null;
        ArrayList successFileList   = new ArrayList();
        boolean success             = true;

        for( int i = 0; i < fileList.length; i++ )
        {
            if ( fileList[i].isDirectory() == true )
            {
                continue;
            }

            try
            {
                // Parse Files to get Object List
                if ( fileList[i].getName().startsWith( "Pricing" ) )
                {
                    ArrayList priceRangeList = parsePriceRangeReport( fileList[i].getAbsolutePath() );
                    if ( priceRangeList != null && priceRangeList.size() > 0 )
                    {
                        PricingDAO.saveAllPricingDetails( dbTransaction, priceRangeList );
                    }

                    successFileList.add( fileList[ i ] );
                }
            }
            catch ( Exception  e )
            {
                success = false;
                log( "Exception while parsing and storing file: " + fileList[i].getAbsolutePath() + "\nException: " + e );
                e.printStackTrace();
                throw e;
            }
        }

        if( success == true )
        {
            System.out.println( "SUCCESSFULLY UPDATED IN THE DATABASE" );
        }
         // Move the successful files to 'done' directory
        if ( success == true )
        {
            String tempFileName = null;
            String tempDestFileName = null;
            File tempFile = null;
            int successFileListSize = successFileList.size();

            for ( int i = 0; i < successFileListSize; i++ )
            {
                tempFile = ( File ) successFileList.get( i );
                tempFileName = tempFile.getAbsolutePath();
                tempDestFileName = doneDestDir.getAbsolutePath() + "/" + tempFile.getName();
                AdaptorUtils.fileCopy( tempFileName, tempDestFileName );

                if ( tempFile.delete() == false )
                {
                    log( "WARNING!! WARNING!! WARNING!! Copied " + tempFile.getName() + " to " + doneDestDir.getAbsolutePath() + ", but Could not delete it from the present directory " );
                }
                else
                {
                    log( tempFile.getName() + " has been moved to " + doneDestDir.getAbsolutePath() );
                }
            }
        }
   } // end of execute method.

    /**
     * @param fileName
     * @return
     * @throws Exception
     */
    private ArrayList parsePriceRangeReport(String fileName ) throws Exception
    {
        ArrayList priceRangeList = new ArrayList();
        Pricing priceRangeInfo   = null;
        double [][] regularPriceRange  = null;
        double [][] samplePriceRange   = null;
       
        if (fileName == null)
        {
            throw new ScalarException("Filename argument is null");
        }

        try
        {
            log("\nFound " + fileName);
            log("Parsing the file for Price guidelines Report...");
            System.out.println("\nFound " + fileName);
            System.out.println("Parsing the file for guidelines Report...");

            Workbook workbook = Workbook.getWorkbook( new FileInputStream( fileName ) );
            Sheet sheet = workbook.getSheet( 0 );

            Cell[] firstRow = sheet.getRow( 0 );
            Cell[] row = null;

            int rowLength = firstRow.length-4; //subtracting other cells, to take only the range cells given
            int[][] range  = new int[rowLength][2];
            for (int i = 3; i < firstRow.length-1; i++ )
            {
               /* if ( i == 3)
                {
                    range[i-3][0] = 0;
                }
                else
                {
                    range[i-3][0] = range[i-4][1] + 1;
                }*/

               /* if ( firstRow[i].getContents().trim().indexOf("K") != -1 )
                {
                    range[i-3][1] = Integer.parseInt( firstRow[i].getContents().trim().replaceAll("K", "") ) * 1000;

                    //range[i-3] = Integer.parseInt( firstRow[i].getContents().trim().replaceAll("K", "") ) * 1000;
                }
                else if ( firstRow[i].getContents().trim().indexOf("M") != -1 )
                {
                    range[i-3][1] = Integer.parseInt( firstRow[i].getContents().trim().replaceAll("M", "") ) * 1000000;
                }*/
                if ( firstRow[i].getContents() != null )
                {
                    String[] rangeArry = firstRow[i].getContents().trim().split("-");
                    range[i-3][0] =   Integer.parseInt( rangeArry[0] );
                    range[i-3][1] =   Integer.parseInt( rangeArry[1] );
                }
            }

            for ( int rowCount = 1; rowCount < sheet.getRows(); rowCount++ )
            {
                row = sheet.getRow( rowCount );

                priceRangeInfo      = new Pricing();
                regularPriceRange   = new double[rowLength][3];
                samplePriceRange    = new double[rowLength][3];

                if( row.length > 0 )
                {
                    if ( row[0].getType().equals(CellType.EMPTY) )
                    {
                        priceRangeInfo.setMktPartNo( null );
                    }
                    else
                    {
                        priceRangeInfo.setMktPartNo( row[0].getContents().trim() );
                    }
                }
                if( row.length > 1 )
                {
                    if ( row[1].getType().equals(CellType.EMPTY) )
                    {
                        priceRangeInfo.setMktPartNoDesc( null );
                    }
                    else
                    {
                        priceRangeInfo.setMktPartNoDesc( row[1].getContents().trim() ) ;
                    }
                }

                if( row.length > 2 )
                {
                    for ( int fromVal = 3; fromVal < firstRow.length-1 ; fromVal ++ )
                    {
                       samplePriceRange[fromVal-3][0] = range[fromVal-3][0];
                       samplePriceRange[fromVal-3][1] = range[fromVal-3][1];
                       try
                       {
                       
                        samplePriceRange[fromVal-3][2] = Double.parseDouble( row[2].getContents().trim().replaceAll("\\$", "") );
                       }
                       catch(Exception e )
                       {
                          samplePriceRange[fromVal-3][2] = 0;
                       }


                       regularPriceRange[fromVal-3][0] = range[fromVal-3][0];
                       regularPriceRange[fromVal-3][1] = range[fromVal-3][1];
                       try
                       {
                        regularPriceRange[fromVal-3][2] = Double.parseDouble( row[fromVal].getContents().trim().replaceAll("\\$", "") );
                       }
                       catch(Exception e )
                       {
                          regularPriceRange[fromVal-3][2] = 0;
                       }
                    }
                    priceRangeInfo.setSamplePriceRange( samplePriceRange );
                    priceRangeInfo.setRegularPriceRange( regularPriceRange );
                }
                if( row.length > 13)
                {
                    if ( row[13].getType().equals(CellType.EMPTY) )
                    {
                        priceRangeInfo.setQuater( 0 );
                        priceRangeInfo.setYear( 0 );
                    }
                    else
                    {
                        String[] token = row[13].getContents().trim().split(",");
                        priceRangeInfo.setQuater( Integer.parseInt( token[0].trim().replaceAll("Q", "") ) );
                        priceRangeInfo.setYear( Integer.parseInt( token[1].trim() ) );
                    }
                }

                if ( priceRangeInfo.getMktPartNo() != null && priceRangeInfo.getMktPartNo().length() > 0  )
                {
                    //System.out.println("priceRangeInfo = " + priceRangeInfo);
                    priceRangeList.add( priceRangeInfo );
                }
            }
        }
        catch (Exception e)
        {
            throw new ScalarException("Exception " + e);
        }

        return priceRangeList;
    }

   private void printHeader()
   {
      String message = ( "\n\nPrice Setup Uploading Parser running on " + new java.util.Date( System.currentTimeMillis() ) + " -------------+\n" );
      System.out.println( message );
      log( message );
   } // end of printHeader

    private void log( String message )
    {
        if ( message == null ) return;

        if ( m_parserLogger != null )
        {
            m_parserLogger.logDebug( message + LINE_SEPARATOR );
        }
        else
        {
            System.out.println( message );
        }
    } // end of log method
}
